package yaty.lee.ssh2.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import yaty.lee.ssh2.dao.PersonDao;
import yaty.lee.ssh2.model.Person;

@Repository("personDao")
public class PersonDaoImpl implements PersonDao {
	private static final Logger logger = Logger.getLogger(PersonDaoImpl.class);

	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public Person findbyEmplid(Long emplid) {
		Person person = null;
		TypedQuery<Person> query = entityManager.createNamedQuery(
				"person.findByEmplid", Person.class);
		query.setParameter("emplid", emplid);
		try {
			person = query.getSingleResult();
		} catch (NoResultException e) {
			logger.warn("No Person was found with an emplid of " + emplid);
		}
		return person;
	}

	@Override
	public List<Person> findAllEmployees() {
		System.out.println("start+++++" + Person.class.getName());
		TypedQuery<Person> query = entityManager.createQuery("from "
				+ Person.class.getName(), Person.class);
		List<Person> employees = query.getResultList();
		return employees;
	}

	@Override
	public void update(Person person) {
		entityManager.merge(person);
	}

	@Override
	public void delete(Person person) {
		Person deletePerson = entityManager.merge(person);
		entityManager.remove(deletePerson);
	}

	@Override
	public void save(Person person) {
		entityManager.persist(person);
	}

}
